<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use app\admin\model\Comment;
/**
 * 求购接口
 */
class Contribution extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    protected $WantBuy = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->user_id = $this->auth->id;
        // $this->user_id = 1;
        $this->WantBuy = new \app\admin\model\WantBuy;
    }  

     /**
     * 留言(留意后返回最新数据)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/Contribution/comment)
     * @ApiParams   (name="content",type=string,required=true,description="留言内容")
     * @ApiParams   (name="contribution_id",type=int,required=true,description="id")
     */
    public function comment(){
        $params = input();
        $params['user_id'] = $this->user_id;
        $Comment = new Comment($params);
        $Comment->allowField(true)->save();
        $comment = $Comment->with('user')->field("*,FROM_UNIXTIME(createtime,'%Y-%m-%d %H:%i:%s') as createtime")->where('contribution_id',$params['contribution_id'])->order('createtime desc')->select();
        $this->success('评论成功',$comment);
    }

    /**
     * 发布/修改/下架/上架求购
     * @ApiSummary  (修改时传id过来)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/Contribution/post)
     * @ApiParams   (name="id",type=int,required=true,description="修改时候传id过来")
     * @ApiParams   (name="images",type=string,required=false,description="多个图片的情况下用逗号隔开")
     * @ApiParams   (name="phone",type=string,required=false,description="联系方式")
     * @ApiParams   (name="content",type=string,required=false,description="描述详情")
     * @ApiParams   (name="status",type=int,required=false,description="重新上架时候为1，下架时候为3")
     * @ApiReturn   ({
        
        })
     */
      public function post(){
        $params = input();
        $params['user_id'] = $this->user_id;

        if($params['id']){
            $res = $this->WantBuy->isUpdate(true)->save(array_filter($params));
        }else{
            unset($params['id']);
            $res = $this->WantBuy->save(array_filter($params));
        }
        if($res){
            $this->success('操作成功');
        }
      }
  

    /**
    * 获取求购列表 
    **/
    public function index(){
      $return = $this->WantBuy->where('status',1)->with('user')->order('weigh desc')->select();
      $this->success('获取求购列表',$return);
    }

    /**
    * 获取求购详情 
    * @param int $id 求购id
    **/
    public function detail(){
      $return['data'] = $this->WantBuy->with('user')->where(['id'=>input('id')])->find();
      $Comment = new Comment();
      $return['comment'] = $Comment->with('user')->field("*,FROM_UNIXTIME(createtime,'%Y-%m-%d %H:%i:%s') as createtime")->where('contribution_id',input('id'))->order('createtime desc')->select();
      $this->success('获取求购详情',$return);
    }
    
  

}
